<template>
  <div class="sc-design-sm">
    <div class="bg-white q-pa-md">
      <div class="text-h6"><strong>商品列表</strong></div>
      <div class="q-mt-md text-body2 text-grey-8">
        <yq-search
          :search="searchForm"
          :isStatus="'goods_state'"
          :topOptions="[
            { value: '', label: '全部' },
            { value: 0, label: '待审核' },
            { value: 1, label: '上架' },
            { value: 2, label: '不通过' },
            { value: 3, label: '下架' },
          ]"
          @search="searchInfo"
          @add="add"
        ></yq-search>
      </div>
    </div>
    <div class="q-mx-sm q-mt-sm q-pb-md text-grey-8 text-center">
      <sc-page
        :items="goodsListData"
        :per-number="12"
        v-model:currentNumber="initialPagination.page"
        :total="initialPagination.rowsNumber"
        :maxPage="initialPagination.last_page"
        item-class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12"
        @changeInput="changeInput"
      >
        <template v-slot:item="props">
          <q-intersection once transition="scale">
            <sc-shadow>
              <q-card flat class="no-border-radius q-pb-sm">
                <q-chip
                  outline
                  size="sm"
                  :label="
                    props.item.goods_state == 0
                      ? '待审核'
                      : props.item.goods_state == 1
                      ? '上架'
                      : props.item.goods_state == 2
                      ? '不通过'
                      : '下架'
                  "
                  :class="
                    props.item.goods_state == 0
                      ? 'bgState3'
                      : props.item.goods_state == 1
                      ? 'bgState2'
                      : props.item.goods_state == 2
                      ? 'bgState1'
                      : 'bgState4'
                  "
                  class="q-ma-sm absolute-top-right"
                  square
                ></q-chip>
                <q-btn
                  flat
                  round
                  dense
                  color="primary"
                  icon="edit"
                  class="q-ma-sm absolute-bottom-right"
                  style="z-index: 10; right: 30px"
                  v-permission="'/goods/List:detail'"
                  @click="edit(props.item.id, props.item)"
                >
                  <q-tooltip>编辑</q-tooltip>
                </q-btn>
                <q-btn
                  flat
                  round
                  dense
                  color="negative"
                  icon="delete"
                  style="z-index: 10"
                  class="q-ma-sm absolute-bottom-right"
                  v-permission="'/goods/List:delete'"
                >
                  <q-menu
                    transition-show="jump-up"
                    transition-hide="jump-down"
                    content-class="text-center"
                    self="bottom left"
                    anchor="top left"
                    :offset="[60, 5]"
                  >
                    <div class="q-px-sm q-pt-md">
                      <q-icon name="info" color="warning" class="q-mr-sm" />
                      是否删除该商品?
                    </div>
                    <div class="q-gutter-x-sm q-pt-sm q-pb-md">
                      <q-btn
                        color="grey-6"
                        unelevated
                        class="no-border-radius text-body2"
                        padding="2px sm"
                        dense
                        label="取消"
                        v-close-popup
                      ></q-btn>
                      <q-btn
                        color="primary"
                        unelevated
                        class="no-border-radius text-body2"
                        padding="2px sm"
                        dense
                        label="确认"
                        @click="deleteData(props.item.id, props.item)"
                        v-close-popup
                      ></q-btn>
                    </div>
                  </q-menu>
                </q-btn>
                <div class="qImgbox">
                  <q-img
                    :src="props.item.goods_image"
                    width="50%"
                    class="q-mt-md"
                  />
                </div>
                <q-card-section>
                  <q-item-label class="text-bold">{{
                    props.item.goods_name
                  }}</q-item-label>
                  <q-item-label class="text-grey q-py-sm"
                    >{{ props.item.type_name }}
                  </q-item-label>
                  <q-item-label class="text-pink"
                    >¥ {{ props.item.price }} 元</q-item-label
                  >
                </q-card-section>
              </q-card>
            </sc-shadow>
          </q-intersection>
        </template>
      </sc-page>
    </div>
  </div>
  <yq-dialog v-model:lockDialog="lockDialog" :title="title" fulls>
    <template v-slot:yq_dialog_body
      ><list-dialog
        :form="formRole"
        @backList="goodsListInit"
        :cateoptions="cateoptions"
        :goodsTypeoptions="goodsTypeoptions"
    /></template>
  </yq-dialog>
</template>

<script lang="ts" setup>
import { listData } from '../mocklist';
import { Ref } from 'vue';
import { useQuasar } from 'quasar';
import { cloneDeep } from 'lodash-es';
import {
  goodsList,
  goodsDelete,
  categoryAll,
  goodsTypeAll,
  goodsDetail,
} from '@/api/goods';
import ListDialog from './ListDialog.vue';

interface formRoleProps {
  goods_name?: string; //商品名称
  category_id?: any; //分类id
  goods_type?: number; //商品类型id
  goods_image?: string; //商品主图
  goods_content?: string; //商品详情
  is_free_shipping?: number; //是否免邮
  unit?: string; //台
  goods_sort?: number; //排序
  goods_state?: any; //商品状态（0:待审核,1:上架,2:审核不通过,3:下架）
  goods_attr_format?: Array<any>; //商品属性
  goods_spec_format?: Array<any>; //商品规格
  sku?: Array<any>; //商品sku
  images?: Array<any>; //商品图片
  tinymceID?: any;
}

const goodsListData = ref([]);

const initialPagination = ref(
  cloneDeep({
    page: 1, //页码
    rowsPerPage: 12, //每页显示条数
    per_page: 12, //每页显示条数
    rowsNumber: 0, //总条数;
    last_page: 1, //总页数;
  })
);
const lockDialog = ref(false);
const $q = useQuasar();
const title = ref('新建商品');
const formRole: Ref<formRoleProps> = ref({});
const cateoptions: any = ref([]); //所有分类
const goodsTypeoptions: any = ref([]); //商品分类

const searchForm = reactive({
  keywords: '',
  search: {
    goods_state: '',
  },
  dateMin: {
    created_at: '',
  },
  dateMax: {
    created_at: '',
  },
  loading: false,
});
const changeInput = (page: any) => {
  console.log('页码改变changeInput', page);
  initialPagination.value.page = page;
  goodsListInit();
};
const searchInfo = () => {
  console.log('搜索重置');
  initialPagination.value.page = 1;
  goodsListInit();
};
const add = () => {
  title.value = '新建商品';
  formRole.value = {
    goods_state: 0,
    tinymceID:
      'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + ''),
    goods_attr_format: [],
    goods_spec_format: [],
    is_free_shipping: 1,
    sku: [],
    images: [],
  };
  lockDialog.value = true;
  console.log('add', formRole.value);
};
//编辑用户
const edit = async (index: number, item: any) => {
  console.log('edit', item);
  title.value = '编辑商品';
  const detail: any = await goodsDetail({ goods_id: item.goods_id });

  //转回isform.value.sku的结构
  let data = cloneDeep(detail.data);
  data.sku.forEach((item: any, index: any) => {
    item.sku_spec_format.forEach((i: any, d: any) => {
      for (let key in i) {
        if (key == 'spec_name') {
          item[i.spec_name] = i.spec_value;
        }
      }
    });
    delete item.sku_spec_format;
  });
  //分类ID多选框字符串转数组
  data.category_id = data.category_id.split(',').map(Number);
  console.log('转回去最终结果', data);

  formRole.value = cloneDeep(data);
  formRole.value.tinymceID =
    'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '');
  lockDialog.value = true;
  // if (formRole.value.portrait == null) {
  //   formRole.value.portrait = '';
  // }
};
const deleteData = async (index: number, item: any) => {
  const res: any = await goodsDelete({ goods_id: item.goods_id });
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
    initialPagination.value.page = 1;
    goodsListInit();
  }
};
const goodsListInit = async () => {
  lockDialog.value = false;
  searchForm.loading = true;
  const requestInfo = cloneDeep(
    Object.assign(initialPagination.value, searchForm)
  );
  const res: any = await goodsList(requestInfo);
  searchForm.loading = false;
  goodsListData.value = res.data.data;
  initialPagination.value.rowsNumber = res.data.total;
  initialPagination.value.last_page = res.data.last_page;
  const resCate: any = await categoryAll();
  const resType: any = await goodsTypeAll();
  cateoptions.value = resCate.data;
  goodsTypeoptions.value = resType.data;

  console.log('res------------', res);
};
onMounted(() => {
  goodsListInit();
});
</script>

<style lang="scss" scoped>
.example-item {
  height: 289px;
  width: 100%;
}
//不通过
.bgState1 {
  background: red !important;
  color: #fff !important;
}
//上架
.bgState2 {
  background: #e8f5e9 !important;
  color: #21ba45 !important;
  border: 1px solid rgb(33, 186, 69) !important;
}
//待审核
.bgState3 {
  background: #fff3e0 !important;
  color: #ff9800 !important;
  border: 1px solid orange !important;
}
//下架状态
.bgState4 {
  background: #f5f5f5 !important;
  color: #000 !important;
  border: 1px solid #f5f5f5 !important;
}
.qImgbox {
  display: flex;
  justify-content: center;
  align-items: center;
  // height: 100%;
}
</style>
